package com.ndbg.demo.service.sign.impl;

import cn.hutool.core.util.URLUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import com.ndbg.demo.model.sign.ESignRequest;
import com.ndbg.demo.model.sign.SignHeadRequest;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Set;
import java.util.TreeMap;

/**
 * @author chenXB
 * @createTime 2023年09月11日 16:52:00
 */
public abstract class AbstractSign {
    private SignHeadRequest signHeadRequest;

    public AbstractSign(SignHeadRequest signHeadRequest) {
        this.signHeadRequest = signHeadRequest;
    }

    public JSONObject assembleHead(ESignRequest eSignRequest) {
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        JSONObject headObject = new JSONObject();
        headObject.put("appId", signHeadRequest.getAppId());
        headObject.put("timeStamp", timestamp);
        headObject.put("projectKey", signHeadRequest.getProjectKey());
        headObject.put("methodCode", eSignRequest.getMethodCode());
        return headObject;
    }


    public String doSign(JSONObject headObject, String bodyStr) {
        JSONObject jsonObject = new JSONObject();
        headObject.put("body", bodyStr);
        String sign = requestBodySignWithSha256(headObject, signHeadRequest.getAppSecret());
        headObject.put("sign", sign);
        headObject.remove("body");
        jsonObject.put("header", headObject);
        jsonObject.put("body", bodyStr);
        HttpResponse httpResponse = HttpRequest.post(signHeadRequest.getUrl()).body(jsonObject.toJSONString()).execute();
        String result = null;
        if (httpResponse.isOk()) {
            result = httpResponse.body();
        } else {
            result = "response error status = " + httpResponse.getStatus();
        }
        System.out.println("结果：" + result);
        return result;
    }


    public static String requestBodySignWithSha256(JSONObject requestBody, String appSecret) {
        requestBody.remove("sign");
        Set<String> setStr = requestBody.keySet();
        TreeMap<String, Object> treeMap = new TreeMap<>();
        for (String key : setStr) {
            String value = requestBody.getString(key);
            if (isNotEmpty(value)) {
                treeMap.put(key, value);
            }
        }
        String signQuery = URLUtil.buildQuery(treeMap, null).concat(appSecret);
        // System.out.println("wait sign = " + signQuery);

        String sign = SecureUtil.sha256(signQuery);
        //System.out.println("sign = " + sign);
        return sign;
    }

    public static boolean isEmpty(String str) {
        return str == null || str.length() == 0;
    }

    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }
}
